package com.java1412.service.impl;

import com.java1412.dao.db1.GoodsRepository;
import com.java1412.entity.db1.Goods;
import com.java1412.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 注意：此处一定要通过@Transactional注解来明确指明所用的事务管理器，否则当多数据源时可能只能执行一个数据库的增删改操作.
 * 且此处应该设置Spring的事务传播属性为propagation = Propagation.NEVER，不使用单个数据源自己的事务，统一交由jtaTransactionManager的事务来管理.
 */
@Service
@Transactional(transactionManager = "goodsTransactionManager", rollbackFor = Exception.class, propagation = Propagation.NEVER)
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsRepository goodsRepository;
    @Override
    public List<Goods> findAll() {
        return goodsRepository.findAll();
    }
    @Override
    public Goods addGoods(Goods goods) {
        try {
            return goodsRepository.save(goods);
        } catch (Exception e) {
            e.printStackTrace();
            // 强制手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }
}
